namespace OneWorks.Utils.FluentData
{
    using System.Collections.Generic;
    using System.Dynamic;

    internal class DynamicTypeAutoMapper
    {
        private readonly List<DataReaderField> _fields;
        private readonly System.Data.IDataReader _reader;

        public DynamicTypeAutoMapper(System.Data.IDataReader reader)
        {
            this._reader = reader;
            this._fields = DataReaderHelper.GetDataReaderFields(this._reader);
        }

        public ExpandoObject AutoMap()
        {
            var item = new ExpandoObject();

            var itemDictionary = (IDictionary<string, object>) item;

            foreach (var column in this._fields)
            {
                if (this._reader.IsDBNull(column.Index))
                    itemDictionary.Add(column.Name, null);
                else
                    itemDictionary.Add(column.Name, this._reader[column.Index]);
            }

            return item;
        }
    }
}